package cn.zyl.demo.common.boot.beans;

import cn.zyl.demo.common.boot.annotation.MethodHandleBoot;
import cn.zyl.demo.common.boot.constant.CommonBootConstant;
import cn.zyl.demo.common.boot.enums.MethodHandleEnum;
import cn.zyl.demo.common.boot.operation.AbstractMethodHandleType;
import org.aspectj.lang.ProceedingJoinPoint;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * MethodHandleBean类说明: 接口收尾处理的方法信息收集实体类
 *
 * @author wsz
 * @version v1.0
 * @date 2020-08-04
 */
public class MethodHandleBean {
    /**  方法-参数列表 */
    private List<Object> params;
    /**  方法-类名 */
    private String clzss;
    /**  方法-方法名 */
    private String method;
    /**  方法-返回值 */
    private String res;
    /**  方法-开始时间-纳秒 */
    private Long startTime;
    /**  方法-统计耗时 */
    private String time;
    /**  方法-功能说明 */
    private String name;
    /**  方法-操作类型 */
    private MethodHandleEnum type;
    /**  方法-自定义处理函数使用 */
    private Boolean record;
    public MethodHandleBean(ProceedingJoinPoint proceedingJoinPoint, MethodHandleBoot handle){
        init(proceedingJoinPoint, handle);
    }
    private void init(ProceedingJoinPoint point, MethodHandleBoot handle){
        this.name = handle.value();
        Object[] arg = point.getArgs();
        this.params = (null == arg || arg.length <= CommonBootConstant.NUM_0) ?new ArrayList<>(CommonBootConstant.NUM_0): Arrays.asList(arg);
        this.clzss = point.getTarget().getClass().getName();
        this.method = point.getSignature().getName();
    }
    public void startRecord(AbstractMethodHandleType handleType){
        this.type = handleType.getType();
        this.record = handleType.getRecord();
        this.startTime = System.nanoTime();
    }
    public void endRecord(Object result){
        /*  方法-结束时间 */
        Long endTime = System.nanoTime();
        this.time = String.valueOf(endTime - this.startTime).replaceAll(CommonBootConstant.LONG_TO_STR_MONEY_REGEX, CommonBootConstant.LONG_TO_STR_MONEY_SPLIT);
        if(null == result){
            this.res = CommonBootConstant.VOID_STR;
        }else {
            this.res = result.toString();
            if(this.res.length() > CommonBootConstant.NUM_50){
                this.res = this.res.substring(CommonBootConstant.NUM_0, CommonBootConstant.NUM_40)+CommonBootConstant.LOG_END_STR;
            }
        }
    }
    @Override
    public String toString() {
        return "{" +
                ", 接口名='" + name + '\'' +
                ", 类型=" + type.getVal() +
                ", 参数=" + params +
                ", 类='" + clzss + '\'' +
                ", 方法='" + method + '\'' +
                ", 结果=" + res +
                ", 耗时(纳秒)=" + time +
                ", record=" + record +
                '}';
    }
}
